package com.nl.lib_project.datas

import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.nl.lib_core.BaseApplication

/** 作者: wangfei 创建时间: 2021/10/11 包名: com.nl.lib_project.datas 类名: NLDatabase */
// @Database(entities = [QuestionnaireResults::class], version = 1, exportSchema = false)
// @TypeConverters(DBConverters::class)
abstract class DatabaseConfig : RoomDatabase() {

  /** 问卷数据表 */
  abstract fun QuestionnaireResultsDao(): QuestionnaireResultsDao

  companion object {
    private val MIGRATION_1_2 =
        object : Migration(1, 2) {
          // 1 表示开始的版本 2 表示结束的版本
          override fun migrate(database: SupportSQLiteDatabase) {
            // 需要向表中中插入的列
            //            database.execSQL(
            //                "ALTER TABLE road_map_points add COLUMN txt_count INTEGER NOT NULL
            // DEFAULT -1 ")
          }
        }

    @Volatile private var INSTANCE: DatabaseConfig? = null
    // 使用者调用
    fun getDataBase(): DatabaseConfig {
      return INSTANCE
          ?: synchronized(DatabaseConfig::class.java) {
            INSTANCE ?: buildDatabase().also { INSTANCE = it }
          }
    }
    private fun buildDatabase(): DatabaseConfig {
      return Room.databaseBuilder(
              BaseApplication.instance!!.baseContext,
              DatabaseConfig::class.java,
              "nl_questionnaire.db")
          .addCallback(object : RoomDatabase.Callback() {})
          .addMigrations(MIGRATION_1_2)
          .build()
    }
  }
}
